import { defineStore } from "pinia";
import {
  login,
  getUserInfo,
  getUserRights,
  getAthleteIdByUserId
} from "@/network/login";
import localCache from '@/utils/cache'
import {routesMapToMenu} from '@/utils/routeToMenu'
import router from "@/router";
const useLoginStore = defineStore('login', {
  state: () => ({
    token: localCache.getCache('token') || '',
    userId: localCache.getCache('userId') || '',
    username: localCache.getCache('username') || '',
    userInfo: localCache.getCache('userInfo') || {},
    roleId: localCache.getCache('roleId') || '',
    rights: localCache.getCache('rights') || [],
    athleteInfo: localCache.getCache('athleteInfo')||{}
  }),
  actions: {
    async loginAction(data:any) {
      const res = await login(data)
      if (res) {
        const { token,userId,username } = res.data
        this.token = token
        localCache.setCache('token', token)
        this.userId = userId 
        localCache.setCache('userId', userId)
        this.username = username
        localCache.setCache('username', username)
        const userInfo = await getUserInfo(userId)
        this.userInfo = userInfo.data
        localCache.setCache('userInfo', userInfo.data)
        const rights = await getUserRights(userInfo.data.roleId)
        this.rights = rights.data
        localCache.setCache('rights', rights.data)
        if (userInfo.data.roleId === 1) {
          const res = await getAthleteIdByUserId(userId)
          console.log(res,222);
          
          if (Object.keys(res).length !== 0) {
            this.athleteInfo = res.data
            localCache.setCache('athleteInfo',res.data)
          }
        }
        // 动态添加路由
        this.addRoutes()
        
        router.push('/main')
      }
    },
    addRoutes() {
      const routes = routesMapToMenu(this.rights)  
      routes.forEach(route => {
        router.addRoute('main',route)
      })
    }
  }
})

export default useLoginStore
